<template>
  <view class="implement-info">
    <view ref="implementTopRef" class="implement-info-top">
      <view class="implement-info-top-left">
        <view class="implement-info-top-task-name">{{ taskName }}</view>
        <view class="implement-info-top-town-name">{{ townName }}</view>
        <view v-if="Number(status) === 2" class="implement-info-top-task-endtime">完成时间: {{ endtime }}</view>
        <view v-else-if=" Number(status) === 4" class="implement-info-top-task-endtime">完成时间: {{ editTime }}</view>
        <view class="implement-info-top-status">状态:
          <view :class="['implement-info-top-status-filter', (Number(status) === 1 || Number(status) === 5) ? 'blue' : Number(status) === 2 ? 'green' : Number(status) === 3 ? 'red' : 'orange']">
            {{ status | statusFilter }}
          </view>
        </view>
      </view>
      <view v-if="Number(status) === 2" class="implement-info-top-status2">
        <u-image v-if="Number(status) === 2" mode="widthFix" :src="implementStatus2" />
        <u-image v-else mode="widthFix" :src="implementStatus5" />
      </view>
    </view>
    <view v-if="Number(status) === 1 || Number(status) === 3 || Number(status) === 5 || Number(status) === 0" class="implement-info-content">
      <view class="implement-info-content-title">
        审批
      </view>
      <view class="implement-info-content-img">
        <u-image mode="widthFix" :src="implementStatus1" />
      </view>
      <view v-if="Number(status) === 0">
        <view class="implement-info-content-text">
          <view>您还没添加参与人</view>
        </view>
      </view>
      <view v-else>
        <view class="implement-info-content-text">
          <view>Ta还没有完成任务</view>
          <view>您可以点击前往查看任务动态</view>
        </view>
        <view class="implement-info-content-btn">
          <button type="primary" @click="gotoTaskLook">前往查看</button>
        </view>
      </view>

    </view>
    <view v-else-if="Number(status) === 4 || Number(status) === 2" class="implement-info-audit">
      <view v-if="!auditCancelBtn">
        <audit :obj="auditObj" />
        <view v-if="Number(status) === 4" class="implement-info-audit-btn">
          <button type="primary" plain="true" @click="auditCancel">驳 回</button>
          <button type="primary" @click="auditSure">确认完成</button>
        </view>
        <view v-else class="implement-info-audit-btn">
          <button type="primary" @click="gotoTaskLook">前往查看任务动态</button>
        </view>
      </view>
      <u-mask :show="auditCancelBtn">
        <view :style="commentInputStyle" @click="auditCancelBtn = false" />
        <view v-if="auditCancelBtn" class="implement-info-audit-mask" @click.stop="auditCancelBtn = true">
          <Comment-Input ref="commentRef" :input-call-back="commentBack" placeholder="请输入" submit-text="驳回" :inpit-height="350" :submit-color="{color: '#ff654d'}" />
        </view>
        {{ auditCancelBtn }}
      </u-mask>
      <u-mask :show="show" />
    </view>
  </view>
</template>

<script>
// 执行状态
import Audit from './compontents/Audit';
import CommentInput from 'common/commentInput/CommentInput';
import { getAvatar } from '@/api/task/taskDetail';
import getConfig from '@/server/getConfig';
import { approvalList, taskEnd } from '@/api/task';
import { getAppId } from '@/utils/local'; // getAppId()

export default {
  filters: {
    statusFilter(status) {
      if (Number(status) === 1 || Number(status) === 5) {
        return '进行中';
      } else if (Number(status) === 2) {
        return '完 成';
      } else if (Number(status) === 3) {
        return '延 期';
      } else if (Number(status) === 4) {
        return '待审核';
      }
      // else if (Number(status) === 5) {
      //   return '驳回';
      // }
    }
  },
  components: {
    Audit,
    CommentInput
  },
  data() {
    return {
      taskName: '',
      townName: '',
      status: '',
      endtime: '',
      implementStatus1: require('@/static/img/task/implementStatus1.png'),
      implementStatus2: require('@/static/img/task/implementStatus2.png'),
      implementStatus5: require('@/static/img/task/implementStatus5.png'),
      auditCancelBtn: false,
      commentInputStyle: {},
      auditObj: {},
      show: false,
      taskEndData: {
        detailTaskGuid: '', // 子任务唯一标识（projectDetial的detailTaskGuid
        editUser: '',
        files: [],
        status: undefined,
        taskGuid: '', // 任务唯一标识guid
        content: ''
      },
      editTime: '', // 待审核时间
      taskInfoRouteQuery: {}
    };
  },
  created() {
    const { csjProgramName } = this.$store.state.task.resData;
    this.taskName = csjProgramName;
    this.getRoute();
    if (this.status === 2 || this.status === 4) {
      this.getApprovalList();
    }
  },
  mounted() {
    this.getTaskInfoRouteQuery();
  },
  methods: {
    getRoute() {
      const { cEnterpriseName, status, completeTime, detailTaskGuid, taskGuid } = this.$route.query;
      this.townName = cEnterpriseName;
      this.status = Number(status);
      this.endtime = completeTime;
      const userId = uni.getStorageSync('userId');
      this.taskEndData = {
        ...this.taskEndData,
        detailTaskGuid,
        editUser: userId,
        taskGuid
      };
    },

    // 获取审批记录
    async getApprovalList() {
      // 获取审批记录
      const { success, data } = await approvalList({
        detailTaskGuid: this.taskEndData.detailTaskGuid,
        pageSize: 999
      });
      if (success && data.length) {
        const { data: { ApiUrl }} = await getConfig();
        let objLast;
        if (this.status === 4) {
          objLast = data[data.length - 1];
          this.editTime = objLast.editTime;
        } else {
          objLast = data[data.length - 2];
        }
        const imgArr = [];
        // 附件
        objLast.annexIds && objLast.annexIds.forEach(item => {
          imgArr.push({
            imgurl: ApiUrl + 'file/downloadById' + `?id=${item}&fileName=${item}`
          });
        });
        objLast['imgArr'] = imgArr;
        const app_Id = getAppId();
        // 有头像地址数据才发送请求
        const res = await getAvatar({
          avatar: objLast.editUser.avatar,
          avatarId: objLast.editUser.avatarId,
          userId: objLast.editUser.id,
          app_Id
        });
        if (res.success) {
          objLast.img = `data:image/png;base64,${res.data}`;
        }
        this.auditObj = objLast;
      }
    },
    gotoTaskLook() {
      const { taskGuid, cEnterpriseCode } = this.$route.query;
      this.$router.push({
        path: '/moretownview',
        query: {
          taskGuid,
          enterpriseGuid: cEnterpriseCode
        }
      });
    },
    auditSure() {
      uni.showModal({
        title: '确认完成',
        content: '是否确认该任务完成',
        cancelText: '否',
        confirmText: '是',
        success: (res) => {
          if (res.confirm) {
            this.show = true;
            const requestForm = new FormData();
            uni.showLoading({
              title: '提交中',
              mask: true
            });
            const { detailTaskGuid, editUser, taskGuid } = this.taskEndData;
            const params = {
              detailTaskGuid,
              editUser,
              taskGuid,
              status: 2
            };
            const headers = {
              'Content-Type': 'application/x-www-form-urlencoded'
            };
            for (const key in params) {
              requestForm.append(key, params[key]);
            }
            taskEnd(requestForm, headers).then(res => {
              const { success, message } = res;
              uni.hideLoading();
              setTimeout(() => {
                this.show = false;
              }, 2000);
              if (success) {
                uni.showToast({
                  title: message,
                  duration: 2000
                });
                setTimeout(() => {
                  const { guid, programGuid, xzRole, enterpriseCode, status } = this.taskInfoRouteQuery;
                  this.$store.dispatch('task/getTaskDetail', {
                    taskGuid: guid, programGuid, xzRole, enterpriseCode,
                    action: (res, type) => {
                      if (type === '明细') {
                        const query = {
                          guid,
                          programGuid,
                          status,
                          enterpriseCode,
                          xzRole
                        };
                        this.$router.replace({
                          path: '/taskdetail/taskinfo',
                          query
                        });
                      }
                    }
                  });
                }, 2000);
              }
            });
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
    auditCancel() {
      this.commentInputStyle = {
        height: this.$refs.implementTopRef.$el.offsetHeight + 12 + 'px'
      };
      this.auditCancelBtn = true;
    },
    commentBack(value) {
      this.show = true;
      const requestForm = new FormData();
      const { content, takePhotoConfig: { fileList: files }} = value;
      this.taskEndData.content = content;
      this.taskEndData.files = files;
      this.taskEndData.status = 5;
      const headers = files.length ? {
        'Content-Type': 'multipart/form-data'
      } : {
        'Content-Type': 'application/x-www-form-urlencoded'
      };
      files.length && (this.taskEndData['type'] = 'Y0013') && files.forEach(file => requestForm.append('files', file.file));
      for (const key in this.taskEndData) {
        if (key !== 'files') {
          requestForm.append(key, this.taskEndData[key]);
        }
      }
      uni.showLoading({
        title: '提交中',
        mask: true
      });
      taskEnd(requestForm, headers).then(res => {
        const { success, message } = res;
        uni.hideLoading();
        setTimeout(() => {
          this.show = false;
        }, 2000);
        if (success) {
          uni.showToast({
            title: message,
            duration: 2000
          });
          setTimeout(() => {
            const { guid, programGuid, xzRole, enterpriseCode, status } = this.taskInfoRouteQuery;
            this.$store.dispatch('task/getTaskDetail', {
              taskGuid: guid, programGuid, xzRole, enterpriseCode,
              action: (res, type) => {
                if (type === '明细') {
                  const query = {
                    guid,
                    programGuid,
                    status,
                    enterpriseCode,
                    xzRole
                  };
                  this.$router.replace({
                    path: '/taskdetail/taskinfo',
                    query
                  });
                }
              }
            });
          }, 2000);
        }
      });
    },

    getTaskInfoRouteQuery() {
      const arr = this.$store.state.task.taskInfoRouteQuery.split('&');
      const obj = {};
      for (let i = 0; i < arr.length; i++) {
        const k = arr[i].split('=')[0];
        const v = arr[i].split('=')[1];
        if (v === 'false') {
          obj[k] = false;
        } else {
          obj[k] = v;
        }
      }
      this.taskInfoRouteQuery = obj;
    }
  }
};
</script>

<style lang="scss" scoped>
.implement-info{
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  .implement-info-top{
    background-color: #fff;
    padding: 12px;
    display: flex;
    .implement-info-top-left {
      flex: 1;
    }
    .implement-info-top-task-name{
      font-size: 17px;
      color: #303133;
      font-weight: 600;
    }
    .implement-info-top-town-name, .implement-info-top-task-endtime, .implement-info-top-status{
      padding-top: 6px;
      color: #b6b9bf;
      font-weight: 550;
      font-size: 17px;
      font-family: PingFangSC, PingFangSC-Medium;
    }
    .implement-info-top-status{
      display: flex;
      .implement-info-top-status-filter{
        padding-left: 10px;
      }
    }
    .implement-info-top-status{
      .blue{
      color: #4FACFF;
      }
      .red {
        color: #FF8168;
      }
      .green {
        color: #2AD28C;
      }
      .orange {
        color: #FFB100;
      }
    }
    .implement-info-top-status2{
      width: 91px;
      height: 86px;
    }
  }
  .implement-info-content{
    margin-top: 12px;
    padding: 12px;
    background-color: #fff;
    flex: 1;
    .implement-info-content-title{
      color: #303133;
      font-size: 17px;
      font-weight: 600;
    }
    .implement-info-content-img{
      padding: 23px;
      padding-top: 100px;
    }
    .implement-info-content-text{
      text-align: center;
      font-weight: 550;
      font-size: 16px;
      & :nth-child(1){
        color: #606266;
      }
      & :nth-child(2){
        color: #b6b9bf;
        padding-top: 4px;
      }
    }
    .implement-info-content-btn{
      padding: 16px 32px 0 32px;
    }
  }
  .implement-info-audit{
    flex: 1;
    background-color: #fff;
    margin-top: 12px;
    .audit{
      padding: 12px;
      margin-top: 12px;
      margin-bottom: 50px;
    }
    .implement-info-audit-btn{
      position: fixed;
      bottom: 0;
      display: flex;
      padding: 12px;
      width: 100%;
      & :nth-child(1){
        flex: 4;
        margin-right: 12px;
      }
      & :nth-child(2){
        flex: 10;
      }
    }
    .implement-info-audit-mask{
      background-color: #fff;
      padding-top: 15px;
      padding-bottom: 15px;
    }
  }
}
</style>
